<template>
    <div>
        <el-card>
            <el-upload
                :on-success="uploadOk"
                class="upload-demo"
                action="http://localhost:3000/set/focus">
                <el-button size="small" type="primary">点击上传轮播图</el-button>
            </el-upload>
            <el-table
            :data="focusData"
            style="width: 100%">
                <el-table-column label="预览" width="500">
                    <template slot-scope="scope">
                        <img v-lazy="`http://localhost:3000/images/focus/${scope.row}`">
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="500">
                    <template slot-scope="scope">
                        <el-button @click="removeFocus(scope.row)" type="danger" icon="el-icon-delete" circle></el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>


    </div>
</template>

<script>
import { ref, onMounted } from '@vue/composition-api';
import axios from 'axios';
export default {
    setup (props, context) {
        axios.defaults.baseURL = 'http://localhost:3000';

        onMounted(() => {
            getFocusData();
        })

        // 轮播图数据
        const focusData = ref([]);
        // 获取轮播图数据
        const getFocusData = async function () {
            let { data: res } = await axios.get('/get/focus');
            if (res.status != 200)
                return context.parent.$message.error('获取轮播图数据失败，请刷新后重试');
            focusData.value = res.focus;
        }

        // 上传轮播图
        const uploadOk = async function (response) {
            if (response.status != 200)
                return context.parent.$message.error('上传轮播图失败，请重试');
            context.parent.$message.success('上传轮播图成功');
            getFocusData();
        }

        // 删除轮播图
        const removeFocus = function (id) {
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                let { data: res } = await axios.delete(`/set/focus/${id}`);
                    if (res.status != 200)
                        return context.parent.$message.error('删除轮播图失败，请重试');
                getFocusData();
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });
            }).catch(() => {
                this.$message({
                  type: 'info',
                  message: '已取消删除'
                });          
            });     
            
        }

        const methods = { uploadOk, removeFocus }
        return {
            ...methods,
            focusData
        }
    }
}
</script>

<style lang="less" scoped>
img {
    width: 100%;
}
</style>